package com.hdax.dm.service;

import com.hdax.dm.dto.CommonResponse;
import com.hdax.dm.dto.DtoUtil;
import com.hdax.dm.dto.item.HotItemDto;
import com.hdax.dm.dto.item.IndexNavTypeDto;
import com.hdax.dm.dto.item.LineNavDto;
import com.hdax.dm.entity.base.DmImage;
import com.hdax.dm.entity.item.DmItem;
import com.hdax.dm.entity.item.DmItemType;
import com.hdax.dm.feign.base.DmImageFeign;
import com.hdax.dm.feign.item.DmItemFeign;
import com.hdax.dm.feign.item.DmItemTypeFeign;
import com.hdax.dm.utils.MokeImage;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class DmItemTypeService {

    @Resource
    private DmItemTypeFeign dmItemTypeFeign;
    @Resource
    private DmItemFeign dmItemFeign;
    @Resource
    private DmImageFeign dmImageFeign;

    //查询分类信息
    public CommonResponse<List<IndexNavTypeDto>> nav(){
        List<DmItemType> parents = dmItemTypeFeign.getItemTypes(0L);
        List<IndexNavTypeDto> indexNavTypeDtos = new ArrayList<>();
        //拷贝一级分类属性
        parents.forEach(parent->{
            IndexNavTypeDto dtoParent = new IndexNavTypeDto();
            BeanUtils.copyProperties(parent,dtoParent);
            //拷贝二级分类属性
            List<DmItemType> childs = dmItemTypeFeign.getItemTypes(parent.getId());
            childs.forEach(child->{
                IndexNavTypeDto dtoChild = new IndexNavTypeDto();
                BeanUtils.copyProperties(child,dtoChild);
                //将二级加入一级
                dtoChild.getChildren().add(dtoChild);
            });
            //将一级加入集合
            indexNavTypeDtos.add(dtoParent);
            //一级对应商品信息
            List<DmItem> dmItems = dmItemFeign.hotItems(parent.getId());
            dmItems.forEach(dmItem -> {
                HotItemDto itemDto = new HotItemDto();
                BeanUtils.copyProperties(dmItem,itemDto);
                DmImage dmImage = dmImageFeign.getImage(2L,1L,dmItem.getId());
                itemDto.setImgUrl(dmImage == null ? MokeImage.getImage(1):dmImage.getImgUrl());
                dtoParent.getHotItems().add(itemDto);
            });
        });
        return DtoUtil.returnSuccess(indexNavTypeDtos);
    }

    //查询横向导航
    public CommonResponse<List<LineNavDto>> lineNav(){
        //拷贝属性
        List<DmItemType> dmItemTypes = dmItemTypeFeign.lineNav();
        List<LineNavDto> lineNavDtos = new ArrayList<>();
        dmItemTypes.forEach(dmItemType -> {
            LineNavDto lineNavDto = new LineNavDto();
            BeanUtils.copyProperties(dmItemType,lineNavDto);
            lineNavDtos.add(lineNavDto);
        });
        return DtoUtil.returnSuccess(lineNavDtos);
    }

    //根据一级查询二级分类信息
    public CommonResponse<List<IndexNavTypeDto>> sortgoods(Long parentId){
        return DtoUtil.returnSuccess(dmItemTypeFeign.getItemTypes(parentId));
    }

}
